import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _slice from "lodash/slice";
import _isArray from "lodash/isArray";
import _forEach from "lodash/forEach";
import _concat from "lodash/concat";
import _cloneDeep from "lodash/cloneDeep";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _dec13, _dec14, _class, _class2;

/**
 * index
 * @date 2018/9/29
 */
import React from 'react';
import { Spin } from 'antd';
import { Bind } from 'lodash-decorators';
import uuid from 'uuid/v4';
import { DndProvider } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import { Content, Header } from 'components/Page';
import { Button as ButtonPermission } from 'components/Permission';
import { openTab } from 'utils/menuTab';
import intl from 'utils/intl';
import formatterCollections from 'utils/intl/formatterCollections';
import PickBoxPanel from "./PickBoxPanel/index";
import DesignerPanel from "./DesignerPanel/index";
import PropPanel from "./PropPanel/index";
import styles from "./index.less?modules";
import { DynamicConfigContext, emptyFieldType } from "./config";
import { convertExtraTemplates, convertParseTemplates, convertInitExtraTemplate, convertInitExtraField } from "./convertUtils";
var PageDesigner = (_dec = formatterCollections({
  code: ['cpfm.ui']
}), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec12 = Bind(), _dec13 = Bind(), _dec14 = Bind(), _dec(_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(PageDesigner, _React$Component);

  var _super = _createSuper(PageDesigner);

  // 存储 DesignerPanel 中 组件的 this
  function PageDesigner(props) {
    var _this;

    _classCallCheck(this, PageDesigner);

    _this = _super.call(this, props);
    _this.renderRefs = {};
    _this.state = {
      config: {},
      // 给定左侧 可添加的组件类型
      activeComponentCode: '',
      // 属性编辑界面
      currentEditComponent: {},
      currentEditField: {},
      // 属性编辑组件的key(用来刷新右侧属性区域)
      propKey: uuid(),
      // 提供给 context 的值
      contextState: {}
    };
    return _this;
  }

  _createClass(PageDesigner, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.queryDetail();
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          _this$props$saving = _this$props.saving,
          saving = _this$props$saving === void 0 ? false : _this$props$saving,
          _this$props$fetching = _this$props.fetching,
          fetching = _this$props$fetching === void 0 ? false : _this$props$fetching,
          bankPath = _this$props.bankPath,
          match = _this$props.match;
      var contextState = this.state.contextState;
      return /*#__PURE__*/React.createElement(DndProvider, {
        backend: HTML5Backend
      }, /*#__PURE__*/React.createElement(DynamicConfigContext.Provider, {
        value: contextState
      }, /*#__PURE__*/React.createElement(Header, {
        title: intl.get('cpfm.ui.model.page.configure').d('页面配置'),
        backPath: bankPath
      }, /*#__PURE__*/React.createElement(ButtonPermission, {
        type: "primary",
        permissionList: [{
          code: "".concat(match.path, ".button.save"),
          type: 'button',
          meaning: '页面自定义页面配置-保存'
        }],
        onClick: this.handleSaveBtnClick,
        loading: saving
      }, intl.get('cpaas.common.button.save').d('保存')), /*#__PURE__*/React.createElement(ButtonPermission, {
        permissionList: [{
          code: "".concat(match.path, ".button.preview"),
          type: 'button',
          meaning: '页面自定义页面配置-预览'
        }],
        onClick: this.handleGotoPreview
      }, intl.get('cpaas.common.button.preview').d('预览'))), /*#__PURE__*/React.createElement(Content, {
        style: {
          padding: 0,
          display: 'flex',
          flexDirection: 'column'
        }
      }, /*#__PURE__*/React.createElement("div", {
        className: styles['dynamic-config']
      }, /*#__PURE__*/React.createElement("div", {
        className: styles['pick-box-panel']
      }, /*#__PURE__*/React.createElement(Spin, {
        spinning: saving || fetching
      }, this.renderPickBoxPanel())), /*#__PURE__*/React.createElement("div", {
        className: styles['designer-panel']
      }, /*#__PURE__*/React.createElement(Spin, {
        spinning: saving || fetching
      }, this.renderDesignerPanel())), /*#__PURE__*/React.createElement("div", {
        className: styles['prop-panel']
      }, /*#__PURE__*/React.createElement(Spin, {
        spinning: saving || fetching
      }, this.renderPropPanel()))))));
    }
    /**
     * 查询页面信息
     */

  }, {
    key: "queryDetail",
    value: function queryDetail() {
      var _this2 = this;

      var getPageDetail = this.props.getPageDetail;
      getPageDetail().then(function () {
        var _this2$props$uiPage = _this2.props.uiPage,
            detailIdp = _this2$props$uiPage.detailIdp,
            config = _this2$props$uiPage.config;
        var _this2$state$contextS = _this2.state.contextState,
            contextState = _this2$state$contextS === void 0 ? {} : _this2$state$contextS;

        var newConfig = _cloneDeep(config);

        var newTemplates = convertExtraTemplates(newConfig.fields, {
          noCloneDeep: true
        });
        newConfig.fields = newTemplates;

        _this2.setState({
          contextState: _objectSpread({
            idp: detailIdp
          }, contextState),
          config: newConfig
        });
      });
    }
    /**
     * 保存按钮点击
     */

  }, {
    key: "handleSaveBtnClick",
    value: function handleSaveBtnClick() {
      var _this3 = this;

      var _this$props2 = this.props,
          prevConfig = _this$props2.uiPage.config,
          onSave = _this$props2.onSave;
      var _this$state$config = this.state.config,
          config = _this$state$config === void 0 ? {} : _this$state$config;

      var saveConfig = _cloneDeep(config);

      var newTemplates = convertParseTemplates(saveConfig.fields, {
        noCloneDeep: true,
        refs: this.renderRefs
      });
      saveConfig.fields = newTemplates;
      onSave(saveConfig, prevConfig).then(function (res) {
        if (res) {
          // 保存成功
          _this3.queryDetail();
        }
      });
    }
    /**
     * 渲染左侧组件区域
     */

  }, {
    key: "renderPickBoxPanel",
    value: function renderPickBoxPanel() {
      var activeComponentCode = this.state.activeComponentCode;
      return /*#__PURE__*/React.createElement(PickBoxPanel, {
        activeComponentCode: activeComponentCode
      });
    }
    /**
     * 渲染中间编辑区域
     */

  }, {
    key: "renderDesignerPanel",
    value: function renderDesignerPanel() {
      var _this$state = this.state,
          _this$state$config2 = _this$state.config,
          config = _this$state$config2 === void 0 ? [] : _this$state$config2,
          currentEditComponent = _this$state.currentEditComponent,
          currentEditField = _this$state.currentEditField;
      return /*#__PURE__*/React.createElement(DesignerPanel, {
        config: config,
        onAddComponent: this.handleAddComponent,
        onAddField: this.handleAddField,
        onActiveComponent: this.handleActiveComponent,
        onActiveField: this.handleActiveField,
        onSwapField: this.handleSwapField,
        onRemoveField: this.handleRemoveField,
        currentEditComponent: currentEditComponent,
        currentEditField: currentEditField,
        refRender: this.handleRefRender
      });
    }
    /**
     * 渲染组件属性
     */

  }, {
    key: "renderPropPanel",
    value: function renderPropPanel() {
      var _this$state2 = this.state,
          currentEditComponent = _this$state2.currentEditComponent,
          currentEditField = _this$state2.currentEditField,
          propKey = _this$state2.propKey,
          config = _this$state2.config;
      return /*#__PURE__*/React.createElement(PropPanel, {
        component: currentEditComponent,
        field: currentEditField,
        propKey: propKey,
        templates: config && config.fields || [],
        config: config,
        onUpdateConfig: this.handleUpdateConfig,
        onRefresh: this.handleRefresh
      });
    }
    /**
     * 新增容器
     * @param {Object} component - new add component
     */

  }, {
    key: "handleAddComponent",
    value: function handleAddComponent() {
      var component = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var config = this.state.config;

      var newComponent = _cloneDeep(component);

      newComponent.fields = [];
      var newTemplate = convertInitExtraTemplate(newComponent, {
        noCloneDeep: true
      });

      if (newTemplate) {
        this.setState({
          config: _objectSpread(_objectSpread({}, config), {}, {
            fields: [].concat(_toConsumableArray(config.fields), [newTemplate])
          }),
          activeComponentCode: newTemplate.templateType,
          currentEditComponent: newTemplate,
          currentEditField: undefined,
          propKey: uuid()
        });
      }
    }
    /**
     * 新增字段
     * @param {Object} component - drop component
     * @param {Object} field - new add field
     * @param {Object} swapField - drop empty field
     */

  }, {
    key: "handleAddField",
    value: function handleAddField(component, field, swapField) {
      var newField = convertInitExtraField(component, field);

      if (_isArray(component.fields)) {
        var insertIndex = component.fields.length;

        if (swapField) {
          _forEach(component.fields, function (cField, index) {
            insertIndex = index;

            if (cField === swapField) {
              return false;
            }
          });
        } // eslint-disable-next-line


        component.fields = _concat([], _slice(component.fields, 0, insertIndex), [newField], _slice(component.fields, insertIndex));
      } else {
        // eslint-disable-next-line no-param-reassign
        component.fields = [newField];
      }

      this.setState({
        activeComponentCode: component.templateType,
        currentEditComponent: component,
        currentEditField: newField,
        propKey: uuid()
      });
    }
    /**
     * 交换字段
     * @param {Object} component - drop component
     * @param {Object} field - drag field
     * @param {Object} swapField - drop field
     */

  }, {
    key: "handleSwapField",
    value: function handleSwapField(component, field, swapField) {
      var swapIndexs = [];

      _forEach(component.fields, function (cField, index) {
        if (cField === field || cField === swapField) {
          // eslint-disable-next-line
          swapIndexs.push(index);
        }
      });

      if (swapIndexs.length === 2) {
        var tempField = component.fields[swapIndexs[0]]; // eslint-disable-next-line

        component.fields[swapIndexs[0]] = component.fields[swapIndexs[1]]; // eslint-disable-next-line

        component.fields[swapIndexs[1]] = tempField;
      }
    }
    /**
     * 删除字段
     * 只能删除 字段是 一维数组的字段
     */

  }, {
    key: "handleRemoveField",
    value: function handleRemoveField(component, removeField) {
      var _this$state$currentEd = this.state.currentEditField,
          currentEditField = _this$state$currentEd === void 0 ? {} : _this$state$currentEd;

      switch (component.templateType) {
        case 'DynamicTable':
          // eslint-disable-next-line no-param-reassign
          component.renderKey = uuid(); // warn dynamicTable fields update must reRender for react-sortable-pane

          break;

        default:
          break;
      }

      var newFields = [];

      _forEach(component.fields, function (field) {
        if (field.fieldId !== removeField.fieldId) {
          newFields.push(field);
        }
      }); // eslint-disable-next-line no-param-reassign


      component.fields = newFields;
      this.setState({
        currentEditComponent: component,
        currentEditField: currentEditField.fieldId === removeField.fieldId ? undefined : currentEditField
      });
    }
    /**
     * 激活容器
     * @param {Object} component - active component
     */

  }, {
    key: "handleActiveComponent",
    value: function handleActiveComponent() {
      var component = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var _this$state3 = this.state,
          currentEditComponent = _this$state3.currentEditComponent,
          currentEditField = _this$state3.currentEditField;

      if (component === currentEditComponent && !currentEditField) {
        // 当前编辑组件 已激活
        return;
      }

      this.setState({
        activeComponentCode: component.templateType,
        currentEditComponent: component,
        currentEditField: undefined,
        propKey: uuid()
      });
    }
    /**
     * 激活字段
     * @param {Object} component - active filed's component
     * @param {Object} field - active field
     */

  }, {
    key: "handleActiveField",
    value: function handleActiveField(component, field) {
      var _this$state4 = this.state,
          currentEditComponent = _this$state4.currentEditComponent,
          currentEditField = _this$state4.currentEditField;

      if (field.componentType === emptyFieldType || currentEditComponent === component && currentEditField === field) {
        // 不能激活
        // 1. 占位的字段
        // 2. 当前字段已激活
        return;
      }

      this.setState({
        activeComponentCode: component.templateType,
        currentEditComponent: component,
        currentEditField: field,
        propKey: uuid()
      });
    }
  }, {
    key: "handleUpdateConfig",
    value: function handleUpdateConfig() {
      var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      this.setState({
        config: config
      });
    }
    /**
     * 获取当前编辑的页面编码
     */

  }, {
    key: "getPageCode",
    value: function getPageCode() {
      var pageCode = this.props.match.params.pageCode;
      return pageCode;
    }
    /**
     * 打开页面预览
     */

  }, {
    key: "handleGotoPreview",
    value: function handleGotoPreview() {
      var pageCode = this.getPageCode();
      var previewPath = "/cpfm/ui/page/preview/".concat(pageCode);
      openTab({
        key: previewPath,
        path: previewPath,
        icon: 'search',
        title: 'cpaas.common.title.uiPagePreview'
      });
    }
    /**
     * 获取中间编辑区域组件的 ref
     * @param renderKey
     * @param ref
     */

  }, {
    key: "handleRefRender",
    value: function handleRefRender(renderKey, ref) {
      this.renderRefs = _objectSpread(_objectSpread({}, this.renderRefs), {}, _defineProperty({}, renderKey, ref));
    }
    /**
     * 刷新当前页面以更新 设计 或 属性区域内容
     */

  }, {
    key: "handleRefresh",
    value: function handleRefresh() {
      this.forceUpdate();
    }
  }]);

  return PageDesigner;
}(React.Component), (_applyDecoratedDescriptor(_class2.prototype, "queryDetail", [_dec2], Object.getOwnPropertyDescriptor(_class2.prototype, "queryDetail"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleSaveBtnClick", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSaveBtnClick"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleAddComponent", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "handleAddComponent"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleAddField", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "handleAddField"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleSwapField", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSwapField"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleRemoveField", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "handleRemoveField"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleActiveComponent", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "handleActiveComponent"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleActiveField", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "handleActiveField"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleUpdateConfig", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "handleUpdateConfig"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "getPageCode", [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, "getPageCode"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleGotoPreview", [_dec12], Object.getOwnPropertyDescriptor(_class2.prototype, "handleGotoPreview"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleRefRender", [_dec13], Object.getOwnPropertyDescriptor(_class2.prototype, "handleRefRender"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleRefresh", [_dec14], Object.getOwnPropertyDescriptor(_class2.prototype, "handleRefresh"), _class2.prototype)), _class2)) || _class);
export { PageDesigner as default };